// routes/app_router.dart
// ... (无变化)
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';

import '../SplashPage.dart';
import '../api/api_client.dart';
import '../bloc/ai_chat/ai_chat_bloc.dart';
import '../bloc/auth/auth_bloc.dart';
import '../bloc/auth/auth_state.dart';
import '../bloc/profile/company_bloc.dart';
import '../bloc/service/service_bloc.dart';
import '../home.dart';
import '../pages/ai_chat/ai_chat_page.dart';
import '../pages/auth/login_page.dart';
import '../pages/home/home_page.dart';
import '../pages/main_shell.dart';
import '../pages/preview/pic_review.dart';
import '../pages/profile/TaxVerificationPage.dart';
import '../pages/profile/enterprise_selection_page.dart';
import '../pages/profile/profile_page.dart';
import '../api/net/report_page.dart';
import '../pages/report/Income_statement.dart';
import '../pages/report/balance_sheet.dart';
import '../pages/report/tax_detail_page.dart';
import '../pages/report/tax_report.dart';
import '../pages/report/tax_report_select.dart';
import '../pages/services/service_order_detail.dart';
import '../pages/services/services_page.dart';
import '../pages/services/service_order_list.dart';
import '../pages/services/services_page_detail.dart';

class AppRouter {
  final AuthBloc authBloc;
  late final GoRouter router;

  AppRouter(this.authBloc) {
    router = GoRouter(
      initialLocation: '/splash',
      refreshListenable: GoRouterRefreshStream(authBloc.stream),
      routes: _routes,
      redirect: _redirect,
    );
  }

  static final _rootNavigatorKey = GlobalKey<NavigatorState>();
  static final _shellNavigatorKey = GlobalKey<NavigatorState>();

  late final List<RouteBase> _routes = [
    GoRoute(path: '/splash', builder: (context, state) => const SplashPage()),
    GoRoute(path: '/login', builder: (context, state) => const LoginPage()),
    ShellRoute(
      navigatorKey: _shellNavigatorKey,
      builder: (context, state, child) {
        return MainShell(child: child);
      },
      routes: [
        GoRoute(
          path: '/home',
          pageBuilder: (context, state) =>
              const NoTransitionPage(child: HomePage()),
        ),
        GoRoute(
          path: '/report',
          pageBuilder: (context, state) =>
              const NoTransitionPage(child: ReportPage()),
        ),
        // GoRoute(path: '/ai', pageBuilder: (context, state) => const NoTransitionPage(child: AiChatPage())),
        // GoRoute(
        //   path: '/services',
        //   pageBuilder: (context, state) =>
        //       NoTransitionPage(child: BlocProvider(
        //           create: (context) => ServiceBloc(apiClient: ApiClient.instance),
        //           child: const ServicesPage())),
        // ),
        GoRoute(
          path: '/services',
          pageBuilder: (context, state) =>
              NoTransitionPage(child: const ServicesPage()),
        ),
        GoRoute(
          path: '/profile',
          pageBuilder: (context, state) =>
              const NoTransitionPage(child: ProfilePage()),
        ),
      ],
    ),
    // GoRoute(
    //   path: '/ai',
    //   pageBuilder: (context, state) =>
    //       const NoTransitionPage(child: AiPage()),
    // ),

    GoRoute(
      path: '/ai',
      pageBuilder: (context, state) => buildNoTransitionPage(context, state, MultiBlocProvider(
          providers: [
            BlocProvider(create: (context) => AiChatBloc()),
          ],
          child: AiPage())),
    ),

    GoRoute(
      path: '/tax-detail',
      pageBuilder: (context, state) => buildNoTransitionPage(context, state, TaxDetailPage()),
    ),
    GoRoute(
      path: '/company-list',
      // builder: (context, state) => const EnterpriseSelectionPage(),
      // pageBuilder: (context, state) => const NoTransitionPage(child: EnterpriseSelectionPage()),
      pageBuilder: (context, state) => CustomTransitionPage(
        key: state.pageKey,
        child: BlocProvider(
          create: (context) => CompanyBloc(ApiClient.instance),
          child: const EnterpriseSelectionPage(),
        ),
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          const begin = Offset(1.0, 0.0);
          const end = Offset.zero;
          const curve = Curves.ease;

          var tween = Tween(
            begin: begin,
            end: end,
          ).chain(CurveTween(curve: curve));
          var offsetAnimation = animation.drive(tween);

          return SlideTransition(position: offsetAnimation, child: child);
        },
      ),
    ),
    GoRoute(
      path: '/company-listen',
      pageBuilder: (context, state) => buildNoTransitionPage(context, state, EnterpriseSelectionPage()),
    ),
    GoRoute(
      path: '/report_tax_detail',
      pageBuilder: (context, state) => buildNoTransitionPage(context, state, TaxReport()),
    ),
    GoRoute(
      path: '/report_income_statement',
      pageBuilder: (context, state) => buildNoTransitionPage(context, state, IncomeStatement()),
    ),
    GoRoute(
      path: '/report_balance_sheet',
      pageBuilder: (context, state) => buildNoTransitionPage(context, state, TaxBalanceSheetReport()),
    ),
    GoRoute(
      path: '/WheelPickerExample',
      pageBuilder: (context, state) => buildNoTransitionPage(context, state, WheelPickerExample()),
    ),
    GoRoute(path: '/mainhome', builder: (context, state) => const MainPage()),
    // GoRoute(
    //   path: '/service-detail',
    //   pageBuilder: (context, state) => buildNoTransitionPage(context, state, BlocProvider(
    //     create: (context) => ServiceBloc(apiClient: ApiClient.instance),
    //     child: const ServiceOrderDetailPage(),
    //   )
    //   ),
    // ),
    GoRoute(
      path: '/service-detail',
      pageBuilder: (context, state) => buildNoTransitionPage(context, state, const ServiceOrderDetailPage()
      ),
    ),
    GoRoute(
      path: '/service-list',
      pageBuilder: (context, state) => buildNoTransitionPage(context, state, const ServiceOrderListPage()
      ),
    ),
    GoRoute(
      path: '/company_verification',
      pageBuilder: (context, state) => buildNoTransitionPage(context, state, BlocProvider(
          create: (context) => CompanyBloc(ApiClient.instance),
          child: TaxVerificationPage())),
    ),
    GoRoute(
      path: '/preview',
      pageBuilder: (context, state) => buildNoTransitionPage(context, state, PicReview(url: state.uri.queryParameters['url'],title: state.uri.queryParameters['title'])),
    ),
    GoRoute(
      path: '/services-detail',
      pageBuilder: (context, state) => buildNoTransitionPage(context, state, ServicesPageDetail()),
    ),
  ];

  Page buildNoTransitionPage(
    BuildContext context,
    GoRouterState state,
    Widget child,
  ) {
    return CustomTransitionPage(
      key: state.pageKey,
      child: child,
      transitionsBuilder: (context, animation, secondaryAnimation, child) {
        const begin = Offset(1.0, 0.0);
        const end = Offset.zero;
        const curve = Curves.ease;
        var tween = Tween(
          begin: begin,
          end: end,
        ).chain(CurveTween(curve: curve));
        var offsetAnimation = animation.drive(tween);
        return SlideTransition(position: offsetAnimation, child: child);
      },
    );
  }

  String? _redirect(BuildContext context, GoRouterState state) {
    final authState = authBloc.state;
    final location = state.matchedLocation;
    print('_redirect    ${authBloc.state}');
    print('location    ${location}');

    // If the user is not logged in and not on the login page, redirect to login
    if (authState is AuthLoading ||
        authState is AuthFailure ||
        authState is AuthFailCode) {
      return null;
    }

    // While the app is starting, stay on the splash screen
    if (authState is AuthInitial || authState is AuthLoading) {
      return location == '/splash' ? null : '/splash';
    }

    final bool loggedIn = authState is AuthAuthenticated;
    final bool isAtLogin = location == '/login';
    final bool isAtSplash = location == '/splash';

    // If the user is not logged in and not on the login page, redirect to login
    if (!loggedIn && !isAtLogin) {
      return '/login';
    }

    // If the user is logged in and on the login or splash page, redirect to home
    if (loggedIn && (isAtLogin || isAtSplash)) {
      // return '/home';
      return '/mainhome';
    }
    // 如果已经在 /mainhome 页面，不再重定向
    if (location == '/mainhome') {
      return null;
    }
    // No redirect needed
    return null;
  }
}

// Helper class to make GoRouter listen to Bloc stream
class GoRouterRefreshStream extends ChangeNotifier {
  GoRouterRefreshStream(Stream<dynamic> stream) {
    notifyListeners();
    stream.asBroadcastStream().listen((_) => notifyListeners());
  }
}
